package com.yue.lin.service;

import com.yue.lin.entity.Teacher;
import com.yue.lin.mapper.TeacherMapper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author zhengyl
 * @description
 * @date 2020-04-23 10:04
 */
@Service
public class TeacherService {
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    public Teacher get(String id) {
        return teacherMapper.get(id);
    }

    public Teacher get2(String id) {
        return teacherMapper.get2(id);
    }

    public List<Teacher> list(String id) {
        return teacherMapper.list(id);
    }

    public int add(Teacher teacher) {
        return teacherMapper.add(teacher);
    }

    //批量插入方式一
    public boolean addBatch() {
        List<Teacher> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Teacher teacher = new Teacher();
            teacher.setName("小帅" + i);
            teacher.setAge(i);
            teacher.setAddress("南天门" + i);
            list.add(teacher);
        }
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);//关闭session的自动提交;
        //        SqlSession sqlSession = sqlSessionFactory.getObject().openSession(ExecutorType.BATCH);
        try {
            TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
            for (Teacher teacher : list) {
                mapper.add(teacher);
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    //批量插入方式二
    public int addBatch2() {
        List<Teacher> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Teacher teacher = new Teacher();
            teacher.setId(UUID.randomUUID().toString().replace("-", ""));
            teacher.setName("小帅" + i);
            teacher.setAge(i);
            teacher.setAddress("南天门" + i);
            list.add(teacher);
        }
        return teacherMapper.batchInsert(list);
    }
}
